var ResponObj = require("./lib/responObj");
var RESTlist = fs.lsAll(__dirname + "/RESTAPI").filter(function(fileName) {
	return fileName.endWith(".api.js");
});
// process.on('uncaughtException', function(err) {

// });
module.exports = function setRouter(app) {
	RESTlist.forEach(function(fileName) {
		var RESTModule = require(fileName);
		var prefix = RESTModule.prefix;
		// console.log("运行", fileName, "模块到：", prefix);
		if (RESTModule.init) {
			RESTModule.init(app);
			delete RESTModule.init;
		}
		delete RESTModule.prefix;
		var methodNames = Object.keys(RESTModule);
		methodNames.forEach(function(methodName) {
			var methodSet = RESTModule[methodName];
			Object.keys(methodSet).forEach(function(extendURL) {

				var method = methodSet[extendURL];
				var handles = [function(req, res, next) {
					var time_anchor = "[" + req.method + "]" + req.url;
					console.time(time_anchor);
					// x-response-time 计算响应时间
					// logger 打印请求日志
					var start = new Date;
					var _body;
					var _self = Object.create(req);
					global.current_req = _self;
					Object.setCci("request", req);
					Object.setCci("response", res);
					Object.setCci("app", _self);
					_self.request = req;
					_self.response = res;
					_self.cookies = {
							set: function() {
								return res.cookie.apply(res, arguments);
							},
							get: function(name) {
								return req.cookies[name];
							}
						}
						//注册全局
					global.current_response = _self;

					_self.__defineGetter__("body", function() {
						return _body;
					});

					_self.__defineSetter__("body", function(v) {
						var ms = new Date - start;
						console.timeEnd(time_anchor);
						if (_body) {
							console.group("相应已经返回并关闭，无法再次发送数据", _body, v);
							console.log("已发送的数据：", _body);
							console.log("未发送的数据：", v);
							console.groupEnd();
							return;
						}
						_body = v;
						res.send(_body);
						//相应完毕，关闭全局注册
						global.current_response = null;
					});
					FiberRun(function() {
						method.call(_self, req, res, next);
					});
				}];
				if (method instanceof Array) {
					handles.unshift.apply(handles, method.splice(0, method.length - 1));
					method = method[method.length - 1];
				}
				handles.unshift(prefix + (extendURL === "/" ? "" : extendURL));
				//只格式化中文不格式化"/"
				handles[0] = encodeURI(handles[0]);
				app[methodName].apply(app, handles);
			});
		});
	});
	console.log("API初始化完成！");
	app.use(function errorHandler(err, req, res, next) {
		console.group("app error");
		console.error(">", err.message, "<\n", err.stack);
		console.groupEnd();

		var _self = global.current_response;
		if (_self) {
			_self.body = ResponObj("error", err.message || err);
		}
	});
}